<!--
/**
* @description 角色管理
* @author wind-lc
* @date 2020-05-11
*/
-->
<template>
  <div>
     <!-- 顶部控件 -->
    <a-form-model :model="searchForm"
                  layout="inline"
                  class="index-search-form-model"
    >
      <a-form-model-item label="角色名称"
                         prop="name">
        <a-input v-model="searchForm.name"
                 allowClear
                 placeholder="请输入角色名称">
        </a-input>
      </a-form-model-item>
      <a-form-model-item label="角色状态"
                         prop="status">
        <a-select v-model="searchForm.status"
                  allowClear
                  placeholder="请选择角色状态">
          <a-select-option v-for="(item,index) in operateData.dataDictionary.status"
                           :key="index"
                           :value="item.value">{{item.name}}</a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item label="创建时间"
                         prop="startEndTime">
        <a-range-picker v-model="searchForm.startEndTime"
                        allowClear></a-range-picker>
      </a-form-model-item>
      <a-form-model-item :wrapper-col="{ span: 24 }"
                         class="top-widget-btn">
        <a-button type="primary"
                  icon="search"
                  shape="round"
                  @click="queryListBycondition">查询</a-button>
        <a-button icon="retweet"
                  shape="round"
                  @click="resetSearch">重置</a-button>
      </a-form-model-item>
    </a-form-model>
    <!-- 顶部控件 -->
    <div class="page"
         :loading="true">
      <form-loading :formLoadingVisible="!pageReady"></form-loading>
      <div class="table-opt-btns">
        <a-button type="primary"
                  icon="plus"
                  @click="addRole">新增</a-button>
        <a-button :disabled="!isSelecte"
                  icon="delete"
                  @click="batchRemove">批量删除</a-button>
      </div>
      <!-- 表格 -->
      <a-table :columns="columns"
               :customRow="tableCustomRow"
               :dataSource="data"
               rowKey="id"
               :rowSelection="{selectedRowKeys: selectedRowKeys,onChange: selectedRowChange}"
               bordered
               :loading="tableLoading"
               @change="tableChange"
               :pagination="pagination">
        <div slot="operation"
             slot-scope="text,record,index"
             class="tabe-button">
          <a-button size="small"
                    type="primary"
                    icon="edit"
                    @click="editRole(record)">编辑</a-button>
          <a-button size="small"
                    type="danger"
                    icon="close"
                    @click="deleteRole(text, record, index)">删除</a-button>
        </div>
      </a-table>
      <!-- 表格 -->
      <!-- 新增编辑表格 -->
      <operate-table :operateVisible.sync="operateVisible"
                     :operateData="operateData"
                     @handleVisible="handleOperateTableVisible"></operate-table>
      <!-- 新增编辑表格 -->
    </div>
  </div>
</template>
<script>

import { FormModel, Input, Select, DatePicker, Button, Table } from 'ant-design-vue'
import OperateTable from './components/OperateTable'
import { getPageHnRole, deleteByPrimaryKey, deleteBatch } from '@/request/api/permissionManagement/roleManagement'
import { getDictData } from '@/request/api/common'
import { getFinalPageNo } from '@/utils/index'
export default {
  name: 'roleManagement',
  components: {
    AFormModel: FormModel,
    AFormModelItem: FormModel.Item,
    AInput: Input,
    ASelect: Select,
    ASelectOption: Select.Option,
    ARangePicker: DatePicker.RangePicker,
    AButton: Button,
    ATable: Table,
    OperateTable
  },
  data () {
    return {
      // 页面完成
      pageReady: false,
      // 顶部搜索表单
      searchForm: {},
      // 角色表头
      columns: [
        {
          title: '序号',
          align: 'center',
          ellipsis: true,
          width: 80,
          customRender: (text, record, index) => {
            return index + 1
          }
        },
        {
          title: '角色编码',
          align: 'center',
          ellipsis: true,
          dataIndex: 'code'
        },
        {
          title: '角色名称',
          align: 'center',
          ellipsis: true,
          dataIndex: 'name'
        },
        {
          title: '状态',
          align: 'center',
          ellipsis: true,
          dataIndex: 'status',
          customRender: (text, record, index) => {
            let t = ''
            this.operateData.dataDictionary.status.forEach(el => {
              if (el.value === text) {
                t = el.name
              }
            })
            return t
          }
        },
        {
          title: '创建人',
          align: 'center',
          ellipsis: true,
          dataIndex: 'createName'
        },
        {
          title: '创建时间',
          align: 'center',
          ellipsis: true,
          dataIndex: 'createTime'
        },
        {
          title: '操作',
          align: 'center',
          ellipsis: true,
          width: 180,
          scopedSlots: {
            customRender: 'operation'
          }
        }
      ],
      // 表数据
      data: [],
      // 表格loading
      tableLoading: false,
      // 分页配置
      pagination: {
        current: 1, // 当前页数
        pageSize: 10, // 每页显示数量
        showQuickJumper: true, // 跳转
        showSizeChanger: true, // 显示改变每页数量
        total: 0, // 总数
        pageSizeOptions: ['10', '15', '20', '25'],
        showTotal: total => `共 ${total} 条` // 显示总数
      },
      // 选中行
      selectedRowKeys: [],
      // 是否打开新增和编辑抽屉
      operateVisible: false,
      // 新增和编辑抽屉数据
      operateData: {
        type: '',
        row: {},
        dataDictionary: {
          status: []
        }
      }
    }
  },
  computed: {
    // 是否有选中项
    isSelecte () {
      return this.selectedRowKeys.length > 0
    }
  },
  watch: {
    'pagination.current': {
      handler: function (current) {
        this.selectedRowKeys = []
      }
    }
  },
  mounted () {
    this.init()
  },
  methods: {
    // table自定义事件
    tableCustomRow (record) {
      return {
        on: { // 事件
          dblclick: (event) => {
            this.operateVisible = true
            this.operateData.row = record
            this.operateData.type = 'view'
          }
        }
      }
    },
    // 初始化
    async init () {
      // 获取数据字典
      this.operateData.dataDictionary.status = await this.getDataDictionary()
      this.pageReady = true
      // 查询数据
      this.searchData()
    },
    // 获取数据字典
    getDataDictionary () {
      return new Promise((resolve, reject) => {
        getDictData('Y-002').then(res => {
          resolve(res.data['Y-002'])
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 从第一页开始查询
    queryListBycondition () {
      this.pagination.current = 1
      this.searchData()
    },
    // 查询数据
    searchData () {
      this.getRoleList(this.searchForm)
    },
    // 重置
    resetSearch () {
      this.searchForm = {}
      this.queryListBycondition()
    },
    // 获取角色列表
    getRoleList (values) {
      this.tableLoading = true
      const param = {
        name: '',
        status: '',
        createStartTime: '',
        createEndTime: ''
      }
      for (const item in values) {
        if (values[item] && values[item].length > 0) {
          if (item === 'startEndTime') {
            param.createStartTime = this.$moment(values.startEndTime[0]).format('YYYY-MM-DD')
            param.createEndTime = this.$moment(values.startEndTime[1]).format('YYYY-MM-DD')
          } else {
            param[item] = values[item]
          }
        }
      }
      getPageHnRole({
        pageNum: this.pagination.current,
        pageSize: this.pagination.pageSize,
        param: param
      })
        .then(res => {
          this.tableLoading = false
          if (res.code === '0') {
            // 数据中状态，模拟数据
            this.data = res.data.list.map(el => {
              const item = el
              if (!el.status) {
                item.status = true
              }
              return item
            })
            this.pagination.total = res.data.total
          }
        })
        .catch(error => {
          this.tableLoading = false
          console.log(error)
        })
    },
    // 选中行
    selectedRowChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    // 批量删除
    batchRemove () {
      this.$confirm({
        title: '你确定要删除此角色?',
        okText: '是',
        okType: 'danger',
        cancelText: '否',
        onOk: () => {
          deleteBatch(this.selectedRowKeys).then(res => {
            if (res.code === '0') {
              this.$message.success('删除成功!')
              this.pagination.current = getFinalPageNo(
                this.pagination.total,
                this.pagination.current,
                this.pagination.pageSize,
                this.selectedRowKeys.length)
              this.searchData()
              this.selectedRowKeys = []
            }
          }).catch(error => {
            console.log(error)
          })
        }
      })
    },
    // 关闭新增和编辑抽屉
    handleOperateTableVisible (parms) {
      this.operateVisible = parms
      // 新增后重置查询
      if (this.operateData.type === 'add') {
        this.resetSearch()
      } else {
        this.searchData()
      }
    },
    // 新增角色
    addRole () {
      this.operateVisible = true
      this.operateData.type = 'add'
    },
    // 编辑角色
    editRole (record) {
      this.operateVisible = true
      this.operateData.type = 'edit'
      this.operateData.row = record
    },
    // 删除角色
    deleteRole (text, record, index) {
      this.$confirm({
        title: '你确定要删除此角色?',
        okText: '是',
        okType: 'danger',
        cancelText: '否',
        onOk: () => {
          deleteByPrimaryKey({
            id: record.id
          }).then(res => {
            if (res.code === '0') {
              this.$message.success('删除成功!')
              // 从批量删除数组中 去掉当前删除的数据
              if (this.selectedRowKeys.includes(record.id)) {
                const index = this.selectedRowKeys.findIndex((id) => id === record.id)
                this.selectedRowKeys.splice(index, 1)
              }
              this.pagination.current = getFinalPageNo(
                this.pagination.total,
                this.pagination.current,
                this.pagination.pageSize,
                1)
              this.searchData()
            }
          }).catch(error => {
            console.log(error)
          })
        }
      })
    },
    // 表格变动
    tableChange (pagination, filters, sorter) {
      this.pagination = pagination
      this.searchData()
    }
  }
}
</script>
<style lang="scss">
</style>
